package com.goldcn.orderborrow.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.common.CommonTools;
import com.goldcn.common.DataUtils;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CodeGenerator;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ErpBorrowInterfaceCfg;
import com.goldcn.config.ErpInterfaceCfg;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.ErpInterfaceCfgEnum;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.goods.dao.GoodsInfoMapper;
import com.goldcn.goods.dao.GoodsSkuMapper;
import com.goldcn.goods.dto.GoodsInfoWithSkuDto;
import com.goldcn.goods.model.GoodsSku;
import com.goldcn.goods.service.GoodsService;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dao.OrderLogisticsMapper;
import com.goldcn.order.dto.UserAndCountDto;
import com.goldcn.order.dto.UserInfoForOrderDto;
import com.goldcn.order.model.OrderLogistics;
import com.goldcn.order.service.OrderService;
import com.goldcn.orderborrow.dao.GoodsCartBorrowMapper;
import com.goldcn.orderborrow.dao.OrderBorrowItemMapper;
import com.goldcn.orderborrow.dao.OrderBorrowSnapshotMapper;
import com.goldcn.orderborrow.dao.OrderInfoBorrowMapper;
import com.goldcn.orderborrow.dto.*;
import com.goldcn.orderborrow.erpbean.BorrowInfoWithItems;
import com.goldcn.orderborrow.erpbean.BorrowItem;
import com.goldcn.orderborrow.model.*;
import com.google.common.base.Objects;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Tim Peng
 * @version V1.0
 * @Description:借货订单业务类
 * @date 2017-4-19 18:29:10
 */
@Service
@Transactional
@ConfigurationProperties("bank")
public class OrderBorrowService {
    @Autowired
    GoodsCartBorrowService goodsCartBorrowService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    OrderInfoBorrowMapper orderInfoBorrowMapper;

    @Autowired
    OrderBorrowAuditService orderBorrowAuditService;

    @Autowired
    GoodsInfoMapper goodsInfoMapper;

    @Autowired
    OrderBorrowItemMapper orderBorrowItemMapper;

    @Autowired
    OrderBorrowSnapshotMapper orderBorrowSnapshotMapper;

    @Autowired
    GoodsService goodsService;

    @Autowired
    GoodsCartBorrowMapper goodsCartBorrowMapper;

    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    GoodsSkuMapper goodsSkuMapper;

    @Autowired
    ErpBorrowInterfaceCfg erpBorrowInterfaceCfg;

    @Autowired
    ErpInterfaceCfg erpInterfaceCfg;

    @Autowired
    OrderService orderService;

    private static final String GROUP = "orderBorrowService";


    private static Logger logger = LoggerFactory.getLogger(OrderBorrowService.class);

    /**
     * 新增借货单
     *
     * @param addOrderDtoList
     * @return
     * @throws Exception
     */
    @Transactional
    public Object addOrder(List<AddOrderBorrowDto> addOrderDtoList) throws Exception {
        Map<Long, Long> param = new HashMap<Long, Long>();
        Map<Long, Integer> oLevelMap = new HashMap<Long, Integer>();
        List<Long> cartIDList = new ArrayList<Long>();
        Long orderID;
        String mobile = null;
        for (AddOrderBorrowDto addOrderBorrowDto : addOrderDtoList) {
            GoodsCartBorrowMore goodsCartBorrow = new GoodsCartBorrowMore();
            GoodsCartBorrowDto goodsCart1 = goodsCartBorrowService.querySingleMyShoppingCart(addOrderBorrowDto.getCartID());
            if(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SELFCOMPANYID.getCode()).indexOf(goodsCart1.getSellerID().toString())<0){//限制供应商
                throw new ServiceException("暂不支持该供应商借货", RestConst.ErrorCode.FORM_FAIL);
            }
            BeanUtils.copyProperties(goodsCartBorrow, goodsCart1);
            goodsCartBorrow.setGoodsName(goodsCart1.getName());
            goodsCartBorrow.setContactName(addOrderBorrowDto.getContactName());
            goodsCartBorrow.setContactAddress(addOrderBorrowDto.getContactAddress());
            goodsCartBorrow.setContactMobile(addOrderBorrowDto.getContactMobile());

            if(!"".equals(checkContactForAddOrder(addOrderBorrowDto))){//校验收货信息
                throw new ServiceException("您的版本太低,请升级到最新版本");
            }else {
                goodsCartBorrow.setShortAddress(addOrderBorrowDto.getShortAddress());
                goodsCartBorrow.setProvince(addOrderBorrowDto.getProvince());
                goodsCartBorrow.setCity(setCityCode(addOrderBorrowDto.getProvince(),addOrderBorrowDto.getCity()));
                goodsCartBorrow.setDistrict(addOrderBorrowDto.getDistrict());
            }


            if (goodsCartBorrow.getQty() <= 0) {
                throw new ServiceException(goodsCartBorrow.getGoodsName() + "商品数量必须大于0", RestConst.ErrorCode.FORM_FAIL);
            }
            if (goodsCartBorrow.getState() == 0) {
                throw new ServiceException(goodsCartBorrow.getGoodsName() + "购物车商品已经失效", RestConst.ErrorCode.FORM_FAIL);
            }
            if (param.get(goodsCartBorrow.getSellerID()) == null) {
                OrderInfoBorrow orderInfoBorrow = new OrderInfoBorrow();
                orderInfoBorrow.setId(IdGen.get().nextId());
                orderInfoBorrow.setOrderNO(CodeGenerator.INSTANCE.nextId());
                orderInfoBorrow.setState(1);
                orderInfoBorrow.setAddTime(CommonUtils.getCurTimestamp());

                orderInfoBorrow.setContactName(goodsCartBorrow.getContactName());
                orderInfoBorrow.setContactAddress(goodsCartBorrow.getContactAddress());
                orderInfoBorrow.setContactMobile(goodsCartBorrow.getContactMobile());

                orderInfoBorrow.setShortAddress(goodsCartBorrow.getShortAddress());
                orderInfoBorrow.setProvince(goodsCartBorrow.getProvince());
                orderInfoBorrow.setCity(goodsCartBorrow.getCity());
                orderInfoBorrow.setDistrict(goodsCartBorrow.getDistrict());

                orderInfoBorrow.setSellerID(goodsCartBorrow.getSellerID());
                orderInfoBorrow.setSellerName(goodsCartBorrow.getSellerName());
                orderInfoBorrow.setUserID(goodsCartBorrow.getUserID());

                //获取用户下单所需用户及其组织信息
                UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(goodsCartBorrow.getUserID());
                mobile = userInfoForOrderDto.getMobile();
                orderInfoBorrow.setUserName(userInfoForOrderDto.getUserName());
                orderInfoBorrow.setUserMobile(userInfoForOrderDto.getMobile());
                orderInfoBorrow.setBranchID(userInfoForOrderDto.getBranchID());
                orderInfoBorrow.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
                orderInfoBorrow.setSubbranchID(userInfoForOrderDto.getSubbranchID());

                //保存用户组织级别
                oLevelMap.put(orderInfoBorrow.getId(),userInfoForOrderDto.getoLevel());

                orderInfoBorrow.setCompanyID(SystemContext.getCompanyID());


                orderInfoBorrow.setAmount(new BigDecimal("0"));//临时代码，后期去除

                orderInfoBorrowMapper.insertSelective(orderInfoBorrow);

                //将sellerID与oID插入map
                param.put(goodsCartBorrow.getSellerID(), orderInfoBorrow.getId());
                orderID = orderInfoBorrow.getId();
           } else {
                orderID = param.get(goodsCartBorrow.getSellerID());
            }
            OrderBorrowItem orderBorrowItem = new OrderBorrowItem();
            orderBorrowItem.setId(IdGen.get().nextId());
            orderBorrowItem.setOrderID(orderID);
            orderBorrowItem.setQty(goodsCartBorrow.getQty());
            orderBorrowItem.setSkuID(goodsCartBorrow.getSkuID());
            orderBorrowItem.setGoodsID(goodsCartBorrow.getGoodsID());
            orderBorrowItem.setGoodsName(goodsCartBorrow.getGoodsName());
            GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(goodsCartBorrow.getSkuID());
            if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (goodsInfoWithSkuDto.getInventory() < goodsCartBorrow.getQty()) {
                throw new ServiceException("库存不足！", RestConst.ErrorCode.DATABASE_ERROR);
            }
            orderBorrowItem.setGoodsImg(goodsInfoWithSkuDto.getImg());
            orderBorrowItem.setGoodsSku(goodsInfoWithSkuDto.getAttrJson());
            orderBorrowItem.setPrice(goodsInfoWithSkuDto.getPrice());
            BigDecimal bigDecimalQty = new BigDecimal(orderBorrowItem.getQty());
            orderBorrowItem.setAmount(bigDecimalQty.multiply(orderBorrowItem.getPrice())); //总价计算

            orderBorrowItem.setMd5(CommonUtils.MD5(getAmountForMD5(orderBorrowItem.getAmount().toString()) + orderBorrowItem.getQty() + ProConstants.salt));  //价格加密字段
            orderBorrowItem.setCompanyID(SystemContext.getCompanyID());
            orderBorrowItemMapper.insertSelective(orderBorrowItem);

            //插入借货明细快照表
            insertBorrowSnapshot(orderBorrowItem.getId(),addOrderBorrowDto.getCompanyID());

            //获取购物车ID用于删除
            cartIDList.add(goodsCartBorrow.getId());

            //下单减库存
            goodsService.changeInventory(1, orderBorrowItem.getGoodsID(), orderBorrowItem.getSkuID(), orderBorrowItem.getQty(), orderBorrowItem.getId());
        }

        //删除购物车单据
        goodsCartBorrowMapper.deleteByPrimaryKey(cartIDList);

        //获取orderIDList用于添加索引
        List<Long> orderIDList = new ArrayList<>();

        //更新每个订单的总价和商品数量
        for (Long orderID1 : param.values()) {
            orderIDList.add(orderID1);
            int qty = orderBorrowItemMapper.selectqtyByOrderID(orderID1);
            BigDecimal amountTotal = orderBorrowItemMapper.selectSumAmountByOrderID(orderID1);
            String md5 = CommonUtils.MD5(getAmountForMD5(amountTotal.toString()) + qty + ProConstants.salt);//md5加密
            Map<String, Object> param1 = new HashMap<String, Object>();
            param1.put("qty", qty);
            param1.put("id", orderID1);
            param1.put("amount", amountTotal);
            param1.put("md5", md5);
            orderInfoBorrowMapper.updateAmountByPrimaryKey(param1);
        }


        String orderBorrowAuditLevel=getBorrowSetting(SystemContext.getCompanyID());
        if (orderService.isOpenErp()){//ERP同步开启
            for(Long id:orderIDList){
                if(oLevelMap.get(id)==1){//总部员工直接同步ERP
                    orderBorrowAuditService.borrowSendToERP(id);
                }else if ("1".equals(orderBorrowAuditLevel)
                        && orderService.isOpenErp()){//ERP同步开启,二级审核关闭,同步ERP
                    orderBorrowAuditService.borrowSendToERP(id);
                }
            }
        }

        return orderIDList;
    }

    /**
     * 复制借货or立即借货
     *
     * @param buyDto
     * @return
     */
    @Transactional
    public Object copyOrDirectBorrow(CopyOrDirectBorrowDto buyDto) {
        Long orderInfoID = null;
        String mobile = null;
        Integer oLevel=0;
        if (buyDto.getType() == 1) {   //复制下单
            OrderInfoBorrow orderInfoBorrow = orderInfoBorrowMapper.selectByPrimaryKey(buyDto.getOrderID());
            //未归还，未赠送，未销售
            if (orderInfoBorrow.getState() != 7 &&
                    orderInfoBorrow.getState()!=8 && orderInfoBorrow.getState()!=9) {
                throw new ServiceException("原借货尚未完成，不能重复下单", RestConst.ErrorCode.DATABASE_ERROR);
            }
            List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(buyDto.getOrderID());
            OrderInfoBorrow orderInfoBorrowNew=new OrderInfoBorrow();
            orderInfoBorrowNew.setId(IdGen.get().nextId());
            orderInfoBorrowNew.setOrderNO(CodeGenerator.INSTANCE.nextId());
            orderInfoBorrowNew.setState(1);
            if(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SELFCOMPANYID.getCode()).indexOf(orderInfoBorrow.getSellerID().toString())<0){//限制供应商
                throw new ServiceException("暂不支持该供应商借货", RestConst.ErrorCode.FORM_FAIL);
            }
            orderInfoBorrowNew.setSellerID(orderInfoBorrow.getSellerID());
            orderInfoBorrowNew.setSellerName(orderInfoBorrow.getSellerName());
            orderInfoBorrowNew.setQty(orderInfoBorrow.getQty());
            orderInfoBorrowNew.setAmount(orderInfoBorrow.getAmount());
            orderInfoBorrowNew.setBranchID(orderInfoBorrow.getBranchID());
            orderInfoBorrowNew.setTwoLevelBranchID(orderInfoBorrow.getTwoLevelBranchID());
            orderInfoBorrowNew.setSubbranchID(orderInfoBorrow.getSubbranchID());
            orderInfoBorrowNew.setUserID(orderInfoBorrow.getUserID());
            orderInfoBorrowNew.setUserName(orderInfoBorrow.getUserName());
            orderInfoBorrowNew.setUserMobile(orderInfoBorrow.getUserMobile());
            orderInfoBorrowNew.setTakeType(null);


            if(!"".equals(checkContactForBuyNow(buyDto))){
                throw new ServiceException("您的版本太低,请升级到最新版本");
            } else {
                orderInfoBorrowNew.setShortAddress(buyDto.getShortAddress());
                orderInfoBorrowNew.setProvince(buyDto.getProvince());
                orderInfoBorrowNew.setCity(setCityCode(buyDto.getProvince(),buyDto.getCity()));
                orderInfoBorrowNew.setDistrict(buyDto.getDistrict());
            }

            orderInfoBorrowNew.setContactName(buyDto.getContactName());
            orderInfoBorrowNew.setContactAddress(buyDto.getContactAddress());
            orderInfoBorrowNew.setContactMobile(buyDto.getContactMobile());

            orderInfoBorrowNew.setAddTime(CommonUtils.getCurTimestamp());

            //orderInfoBorrowNew.setCompanyID(buyDto.getCompanyID());
            orderInfoBorrowNew.setCompanyID(SystemContext.getCompanyID());
            orderInfoBorrowNew.setMd5(orderInfoBorrow.getMd5());

            orderInfoBorrowMapper.insertSelective(orderInfoBorrowNew);

            orderInfoID = orderInfoBorrowNew.getId();

            for (OrderBorrowItem orderBorrowItem : itemList) {
                GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(orderBorrowItem.getSkuID());
                if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                    throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
                }
                if (goodsInfoWithSkuDto.getInventory() < orderBorrowItem.getQty()) {
                    throw new ServiceException("库存不足！" + orderBorrowItem.getGoodsName(), RestConst.ErrorCode.DATABASE_ERROR);
                }
                orderBorrowItem.setId(IdGen.get().nextId());
                orderBorrowItem.setOrderID(orderInfoBorrowNew.getId());
                orderBorrowItem.setGoodsSku(goodsInfoWithSkuDto.getAttrJson());
                orderBorrowItem.setPrice(goodsInfoWithSkuDto.getPrice());
                BigDecimal bigDecimalQty = new BigDecimal(orderBorrowItem.getQty());
                orderBorrowItem.setAmount(bigDecimalQty.multiply(orderBorrowItem.getPrice())); //总价计算

                orderBorrowItem.setMd5(CommonUtils.MD5(getAmountForMD5(orderBorrowItem.getAmount().toString()) + orderBorrowItem.getQty() + ProConstants.salt));  //价格加密字段
                orderBorrowItem.setCompanyID(SystemContext.getCompanyID());
                orderBorrowItemMapper.insertSelective(orderBorrowItem);

                //插入订单明细快照表
                insertBorrowSnapshot(orderBorrowItem.getId(),buyDto.getCompanyID());

                //下单减库存
                goodsService.changeInventory(1, orderBorrowItem.getGoodsID(), orderBorrowItem.getSkuID(), orderBorrowItem.getQty(), orderBorrowItem.getId());
            }
        } else if (buyDto.getType() == 2) {  //立即借货
            if (buyDto.getQty() <= 0) {
                throw new ServiceException("商品数量必须大于0", RestConst.ErrorCode.FORM_FAIL);
            }
            if(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SELFCOMPANYID.getCode()).indexOf(buyDto.getSellerID().toString())<0){//限制供应商
                throw new ServiceException("暂不支持该供应商借货", RestConst.ErrorCode.FORM_FAIL);
            }
            OrderInfoBorrow orderInfo = new OrderInfoBorrow();
            orderInfo.setId(IdGen.get().nextId());
            orderInfo.setOrderNO(CodeGenerator.INSTANCE.nextId());

            orderInfo.setContactName(buyDto.getContactName());
            orderInfo.setContactAddress(buyDto.getContactAddress());
            orderInfo.setContactMobile(buyDto.getContactMobile());

            orderInfo.setShortAddress(buyDto.getShortAddress());
            orderInfo.setProvince(buyDto.getProvince());
            orderInfo.setCity(buyDto.getCity());
            orderInfo.setDistrict(buyDto.getDistrict());

            orderInfo.setAddTime(CommonUtils.getCurTimestamp());
            orderInfo.setUserID(buyDto.getUserID());
            orderInfo.setState(1);

            if(!"".equals(checkContactForBuyNow(buyDto))){//校验收货信息
                throw new ServiceException("您的版本太低,请升级到最新版本");
            } else {
                orderInfo.setShortAddress(buyDto.getShortAddress());
                orderInfo.setProvince(buyDto.getProvince());
                orderInfo.setCity(setCityCode(buyDto.getProvince(),buyDto.getCity()));
                orderInfo.setDistrict(buyDto.getDistrict());
            }

            orderInfo.setSellerID(buyDto.getSellerID());
            orderInfo.setSellerName(buyDto.getSellerName());

            //orderInfo.setCompanyID(buyDto.getCompanyID());
            orderInfo.setCompanyID(SystemContext.getCompanyID());

            //获取用户下单所需用户及其组织信息
            UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(buyDto.getUserID());
            mobile = userInfoForOrderDto.getMobile();
            orderInfo.setUserName(userInfoForOrderDto.getUserName());
            orderInfo.setUserMobile(userInfoForOrderDto.getMobile());
            orderInfo.setBranchID(userInfoForOrderDto.getBranchID());
            orderInfo.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
            orderInfo.setSubbranchID(userInfoForOrderDto.getSubbranchID());

            oLevel=userInfoForOrderDto.getoLevel();

            orderInfo.setAmount(new BigDecimal("0"));//临时代码，后期去除

            orderInfoBorrowMapper.insertSelective(orderInfo);

            orderInfoID = orderInfo.getId();

            GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(buyDto.getSkuID());
            if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (goodsInfoWithSkuDto.getInventory() < buyDto.getQty()) {
                throw new ServiceException("库存不足！", RestConst.ErrorCode.DATABASE_ERROR);
            }
            OrderBorrowItem orderItem = new OrderBorrowItem();
            orderItem.setId(IdGen.get().nextId());
            orderItem.setOrderID(orderInfo.getId());
            orderItem.setGoodsImg(goodsInfoWithSkuDto.getImg());
            orderItem.setGoodsName(goodsInfoWithSkuDto.getName());
            orderItem.setGoodsID(goodsInfoWithSkuDto.getGoodsID());
            orderItem.setQty(buyDto.getQty());
            orderItem.setSkuID(buyDto.getSkuID());
            orderItem.setGoodsSku(goodsInfoWithSkuDto.getAttrJson());
            orderItem.setPrice(goodsInfoWithSkuDto.getPrice());
            BigDecimal bigDecimalQty = new BigDecimal(buyDto.getQty());
            orderItem.setAmount(bigDecimalQty.multiply(goodsInfoWithSkuDto.getPrice())); //总价计算

            orderItem.setMd5(CommonUtils.MD5(getAmountForMD5(orderItem.getAmount().toString()) + orderItem.getQty() + ProConstants.salt));  //价格加密字段
            orderItem.setCompanyID(SystemContext.getCompanyID());
            orderBorrowItemMapper.insertSelective(orderItem);

            //插入订单明细快照表
            insertBorrowSnapshot(orderItem.getId(),buyDto.getCompanyID());

            //下单减库存
            goodsService.changeInventory(1, orderItem.getGoodsID(), orderItem.getSkuID(), orderItem.getQty(), orderItem.getId());
        } else {
            throw new ServiceException("type参数传入错误", RestConst.ErrorCode.FORM_FAIL);
        }

        int qty = orderBorrowItemMapper.selectqtyByOrderID(orderInfoID);
        BigDecimal amountTotal = orderBorrowItemMapper.selectSumAmountByOrderID(orderInfoID);

        String md5 = CommonUtils.MD5(getAmountForMD5(amountTotal.toString()) + qty + ProConstants.salt);//md5加密
        Map<String, Object> param1 = new HashMap<String, Object>();
        param1.put("id", orderInfoID);
        param1.put("qty", qty);
        param1.put("amount", amountTotal);
        param1.put("md5", md5);
        orderInfoBorrowMapper.updateAmountByPrimaryKey(param1);

        if(oLevel<1){
            //获取用户下单所需用户及其组织信息
            UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(buyDto.getUserID());
            oLevel=userInfoForOrderDto.getoLevel();
        }
        String orderBorrowAuditLevel=getBorrowSetting(SystemContext.getCompanyID());
        if (orderService.isOpenErp()){//ERP同步开启
            if(oLevel==1){//总部员工直接同步ERP
                orderBorrowAuditService.borrowSendToERP(orderInfoID);
            }else if ("1".equals(orderBorrowAuditLevel)
                    && orderService.isOpenErp()){//ERP同步开启,二级审核关闭,同步ERP
                orderBorrowAuditService.borrowSendToERP(orderInfoID);
            }

        }

        List<Long> orderIDNewList = new ArrayList<>();
        orderIDNewList.add(orderInfoID);
        return orderIDNewList;
    }

    /**
     * 获取下订单需要的UserInfo及其组织信息
     *
     * @param userID
     * @return
     */
    public Object getUserInfoForOrder(Long userID) {
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserInfoForOrder + userID, restTemplate);
        //if (jsonObject.get("isSuccess") != 1) {
        if (!Objects.equal(DataUtils.getInteger(jsonObject,"isSuccess"),1)) {
            throw new ServiceException("调用base服务获取用户信息接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (UserInfoForOrderDto) JSONObject.toBean(jsonObject.getJSONObject("data"), UserInfoForOrderDto.class);
    }

    //获取内部员工用户信息及其统计信息[1仅获取用户信息，2并且获取用户统计信息]
    private Object getUserAndCount(Long userID, int type) {
        try {
            JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserForOrderCount + userID + "/" + type, restTemplate);
            return JSONObject.toBean(jsonObject.getJSONObject("data"), UserAndCountDto.class);
        } catch (Exception e) {
            throw new ServiceException("调用base服务失败", e);
        }
    }

    /**
     * 去掉小数点后的0
     *
     * @param amount
     * @return
     */
    private String getAmountForMD5(String amount) {
        if (amount.indexOf(".") > 0) {
            amount = amount.replaceAll("0+?$", "");//去掉多余的0
            amount = amount.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return amount;
    }

    /**
     * 插入借货明细快照表
     *
     * @param itemID
     */
    private void insertBorrowSnapshot(Long itemID,Long companyID) {
        OrderBorrowItem orderItem1 = orderBorrowItemMapper.selectByPrimaryKey(itemID);
        String itemJson = JSONArray.fromObject(orderItem1).toString();
        OrderBorrowSnapshot orderBorrowSnapshot = new OrderBorrowSnapshot();
        orderBorrowSnapshot.setId(IdGen.get().nextId());
        orderBorrowSnapshot.setItemID(orderItem1.getId());
        orderBorrowSnapshot.setJson(itemJson);
        //orderBorrowSnapshot.setCompanyID(companyID);
        orderBorrowSnapshot.setCompanyID(SystemContext.getCompanyID());
        orderBorrowSnapshotMapper.insertSelective(orderBorrowSnapshot);
    }

    /**
     * @param orderID
     * @param type    1查询订单详细信息，2只查询订单信息
     * @return
     * @throws Exception
     */
    public Object selectByOrderID(Long orderID, Long userID, int type) throws Exception {
        OrderInfoBorrow orderInfoBorrow = orderInfoBorrowMapper.selectByPrimaryKey(orderID);
        OrderLogistics orderLogistics = new OrderLogistics();
        Map<String, Object> traceabilityObject = new HashMap<>();
        Map<String, String> receiverMap = new HashMap<>();
        switch (type) {
            case 1:
                orderLogistics = selectLogisticByOrderID(orderID);
                receiverMap = getAddress(orderInfoBorrow);
                break;
            case 2:
                if (orderInfoBorrow.getUserID().equals(userID)) {
                    orderLogistics = selectLogisticByOrderID(orderID);
                    receiverMap = getAddress(orderInfoBorrow);
                }
                break;
        }
        DataResult result = HttpUtil.httpGet(ProConstants.getTraceability + orderInfoBorrow.getUserID(), restTemplate);
        if (result.getIsSuccess() == 1) {
            traceabilityObject = (Map<String, Object>) result.getData();
        } else {
            System.out.print("-----调用base服务查询用户溯源信息失败-----");
        }

        OrderBorrowDto orderDto = new OrderBorrowDto();
        orderDto.setOrderInfoBorrow(orderInfoBorrow);
        orderDto.setTraceabilityObject(traceabilityObject);
        orderDto.setOrderLogistics(orderLogistics);
        orderDto.setReceiver(receiverMap);
        List<OrderBorrowItemMoreDto> moreDtoList = new ArrayList<>();
        List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(orderID);
        for (OrderBorrowItem item : itemList) {
            OrderBorrowItemMoreDto moreDto = new OrderBorrowItemMoreDto();
            BeanUtils.copyProperties(moreDto, item);
            GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(item.getSkuID());
            if (goodsSku == null) {
                moreDto.setInventory(0);
            } else {
                moreDto.setInventory(goodsSku.getInventory());
            }
            moreDtoList.add(moreDto);
        }
        orderDto.setItemList(moreDtoList);
        return orderDto;
    }

    /**
     * 根据orderID查询物流运单信息
     *
     * @param orderID
     * @return
     */
    public OrderLogistics selectLogisticByOrderID(Long orderID) {
        return orderLogisticsMapper.selectByOrderID(orderID);
    }

    /**
     * 获取订单物流信息
     *
     * @param orderInfoBorrow
     * @return
     */
    private Map<String, String> getAddress(OrderInfoBorrow orderInfoBorrow) {
        Map<String, String> map = new HashMap<>();
        if (null != orderInfoBorrow) {
            map.put("address", orderInfoBorrow.getContactAddress());
            map.put("contacts", orderInfoBorrow.getContactName());
            map.put("contactPhone", orderInfoBorrow.getContactMobile());
        } else {
            map.put("address", "未查到");
            map.put("contacts", "未查到");
            map.put("contactPhone", "未查到");
        }
        return map;
    }

    /**
     * 添加物流运单号
     *
     * @param orderLogistics
     * @return
     */
    @Transactional
    public String addLogistics(OrderLogistics orderLogistics) {
        OrderLogistics logistics = orderLogisticsMapper.selectByOrderID(orderLogistics.getOrderID());
        if (logistics != null) {
            orderLogisticsMapper.deleteByPrimaryKey(logistics.getId());
        }
        orderLogistics.setId(IdGen.get().nextId());
        orderLogistics.setAddTime(CommonUtils.getCurTimestamp());
        orderLogistics.setType(2);//借货订单区分
        orderLogisticsMapper.insertSelective(orderLogistics);
        return "success";
    }

    /**
     * ERP添加物流运单号并发货
     * ERP to Me
     * @param orderLogistics
     * @return
     */
    @Transactional
    public String addLogsAndSendForERP(OrderLogistics orderLogistics) {
        logger.info("ERP开始发货借货订单");
        OrderInfoBorrow orderInfoBorrow = orderInfoBorrowMapper.selectByPrimaryKey(orderLogistics.getOrderID());
        if(null==orderInfoBorrow){
            throw CommonTools.createException(ErrorCodeEnum.borrowToERPNofoundException);
        }
        OrderLogistics logistics = orderLogisticsMapper.selectByOrderID(orderLogistics.getOrderID());
        if (logistics != null) {
            orderLogisticsMapper.deleteByPrimaryKey(logistics.getId());
        }
        orderLogistics.setId(IdGen.get().nextId());
        orderLogistics.setAddTime(CommonUtils.getCurTimestamp());
        orderLogistics.setType(2);//借货订单区分
        orderLogisticsMapper.insertSelective(orderLogistics);
        OrderBorrowStateDto stateDto=new OrderBorrowStateDto();
        stateDto.setId(orderLogistics.getOrderID());
        stateDto.setIsERP("1");//ERP发货特殊标识
        stateDto.setState(5);
        updateState(stateDto);
        logger.info("ERP借货发货成功,orderID:" + orderLogistics.getOrderID());
        return "success";

    }

    /**
     * ERP撤回发货
     * ERP to Me
     * 返回到系统已审核状态(31)
     * @param orderID
     * @return
     */
    @Transactional
    public String sendBackForERP(Long orderID) {
        logger.info("ERP开始撤回发货");
        OrderInfoBorrow orderInfoBorrow = orderInfoBorrowMapper.selectByPrimaryKey(orderID);
        if(null==orderInfoBorrow){
            throw CommonTools.createException(ErrorCodeEnum.borrowToERPNofoundException);
        }
        if(5!=orderInfoBorrow.getState()){
            throw CommonTools.createException(ErrorCodeEnum.borrowToERPStateException);
        }
        orderInfoBorrowMapper.sendBackForERP(orderID);
        logger.info("ERP撤回发货成功,orderID:" + orderID);
        return "success";

    }



    /**
     * ERP借货归还
     * ERP to Me
     * @param orderBorrowStateDto
     * @return
     */
    @Transactional
    public String giveBackForERP(OrderBorrowStateDto orderBorrowStateDto) {
        logger.info("ERP开始归还借货订单");
        OrderInfoBorrow orderInfoBorrow = orderInfoBorrowMapper.selectByPrimaryKey(orderBorrowStateDto.getId());
        if(null==orderInfoBorrow){
            throw CommonTools.createException(ErrorCodeEnum.borrowToERPNofoundException);
        }
        OrderBorrowStateDto stateDto=new OrderBorrowStateDto();
        stateDto.setId(orderBorrowStateDto.getId());
        stateDto.setGivebackMarkedID(orderBorrowStateDto.getGivebackMarkedID());
        stateDto.setState(orderBorrowStateDto.getState());
        updateState(stateDto);
        logger.info("ERP借货归还成功,orderID:" + orderBorrowStateDto.getId());
        return "success";
    }

    /**
     * 定时任务（订单未审核超过20小时失效）
     * (暂时废弃)
     * @return
     */
    @Deprecated
    public Object timeTaskOrderCancel() {
        OrderBorrowSelectDto selectDto = new OrderBorrowSelectDto();
        selectDto.setState(1);
        List<OrderInfoBorrow> orderInfoList = orderInfoBorrowMapper.selectListByConditon(selectDto); //1待审核
        if (orderInfoList.size() > 0) {
            for (OrderInfoBorrow oi : orderInfoList) {
                if (CommonUtils.getCurTimestamp() - oi.getAddTime() > 72000000) {
                    OrderBorrowStateDto stateDto = new OrderBorrowStateDto();
                    stateDto.setId(oi.getId());
                    stateDto.setState(0); //取消
                    updateState(stateDto);
                }
            }
        }
        return "success";
    }

    /**
     * 定时任务，发货后超过7天时间则自动确认收货
     *
     * @return
     */
    @Transactional
    public Object timetaskOrderReceipt() {
        OrderBorrowSelectDto selectDto = new OrderBorrowSelectDto();
        selectDto.setState(5);
        List<OrderInfoBorrow> orderInfoList = orderInfoBorrowMapper.selectListByConditon(selectDto); //已发货
        if (orderInfoList.size() > 0) {
            for (OrderInfoBorrow orderInfo : orderInfoList) {
                if (CommonUtils.getCurTimestamp() - orderInfo.getSendTime() > 604800000) {
                    OrderBorrowStateDto stateDto = new OrderBorrowStateDto();
                    stateDto.setId(orderInfo.getId());
                    stateDto.setState(6);   //收货
                    stateDto.setTakeType(2l);//系统自动收货
                    updateState(stateDto);
                }
            }
        }
        return "success";
    }

    /**
     * 触发定时任务，7天时间自动收货
     * 每天00.00执行
     * @return
     */
    public Object setupBorrowOrderReceipt() {
        //启动之前先删除
        restTemplate.delete(ProConstants.QUARTZ + "/commission/" + GROUP);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("taskId", "commission");
        map.put("time", "0 0 0 * * ?");
        map.put("jobUrl", ProConstants.BANK + "/orderborrow/timetaskBorrowOrderReceipt");
        map.put("group", GROUP);
        DataResult dataResult = HttpUtil.httpPost(ProConstants.QUARTZ, map, restTemplate);
        if (dataResult.getIsSuccess() == 0) {
            logger.error("setupTimetaskBorrowOrderReceiptJob ...error");
            return "error";
        }
        logger.info("setupTimetaskBorrowOrderReceiptJob commission...cron={}", map.get("time"));
        logger.info("setupTimetaskBorrowOrderReceiptJob commission...jobUrl={}", map.get("jobUrl"));
        logger.info("setupTimetaskBorrowOrderReceiptJob commission...success");
        return "success";
    }

    /**
     * 修改订单状态
     *
     * @param stateDto
     * @return
     */
    @Transactional
    public boolean updateState(OrderBorrowStateDto stateDto) {
        OrderInfoBorrow orderInfo = orderInfoBorrowMapper.selectByPrimaryKey(stateDto.getId());
        if (orderInfo == null) {
            throw new ServiceException("订单不存在", RestConst.ErrorCode.DATABASE_ERROR);
        }
        switch (stateDto.getState()) {
            case 0:   //取消订单、加库存、修改索引状态
                OrderInfoBorrow order = orderInfoBorrowMapper.selectByPrimaryKey(stateDto.getId());
                if (order.getState() != 1) {
                    throw new ServiceException("订单状态参数有误，不能取消", RestConst.ErrorCode.FORM_FAIL);
                }
                verifyMD5(stateDto.getId());  //验证MD5加密信息
                List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(stateDto.getId());
                for (OrderBorrowItem item : itemList) {
                    goodsService.changeInventory(2, item.getGoodsID(), item.getSkuID(), item.getQty());
                }
                stateDto.setState(0);
                break;
            case 5: //已发货
                OrderInfoBorrow order5 = orderInfoBorrowMapper.selectByPrimaryKey(stateDto.getId());
                if(!"1".equals(stateDto.getIsERP())){//非ERP发货则验证状态
                    if(31!=order5.getState()){
                        throw CommonTools.createException(ErrorCodeEnum.orderBorrowStateError);
                    }
                }
                OrderLogistics orderLogistics = orderLogisticsMapper.selectByOrderID(stateDto.getId());
                if (orderLogistics == null) {
                    throw new ServiceException("请先添加物流运单号信息", RestConst.ErrorCode.DATABASE_ERROR);
                }
                verifyMD5(stateDto.getId());  //验证MD5加密信息
                stateDto.setSendTime(CommonUtils.getCurTimestamp());
                stateDto.setState(5);
                break;
            case 6:  //确认收货
                OrderInfoBorrow order6 = orderInfoBorrowMapper.selectByPrimaryKey(stateDto.getId());
                if (order6.getState() != 5) {
                    throw new ServiceException("订单状态参数有误，不能确认收货", RestConst.ErrorCode.FORM_FAIL);
                }
                verifyMD5(stateDto.getId());  //验证MD5加密信息
                stateDto.setTakeTime(CommonUtils.getCurTimestamp());
                stateDto.setState(6);
                //同步ERP
                orderBorrowAuditService.borrowReceiptToERP(stateDto.getId());
                break;
            case 7://标记归还
                OrderInfoBorrow order7 = orderInfoBorrowMapper.selectByPrimaryKey(stateDto.getId());
                if (order7.getState() != 6) {
                    throw new ServiceException("订单状态参数有误，不能归还", RestConst.ErrorCode.FORM_FAIL);
                }
                if(null==stateDto.getGivebackMarkedID()
                        ||"".equals(stateDto.getGivebackMarkedID())){
                    throw new ServiceException("归还标记人ID不能为空", RestConst.ErrorCode.FORM_FAIL);
                }
                verifyMD5(stateDto.getId());  //验证MD5加密信息
                List<OrderBorrowItem> itemList2 = orderBorrowItemMapper.selectByOrderID(stateDto.getId());
                for (OrderBorrowItem item : itemList2) {//恢复库存
                    goodsService.changeInventory(3, item.getGoodsID(), item.getSkuID(), item.getQty());
                }
                stateDto.setGivebackTime(CommonUtils.getCurTimestamp());
                stateDto.setState(7);
                break;
            case 8://赠送
                OrderInfoBorrow order8 = orderInfoBorrowMapper.selectByPrimaryKey(stateDto.getId());
                if (order8.getState() != 6) {
                    throw new ServiceException("订单状态参数有误，不能赠送", RestConst.ErrorCode.FORM_FAIL);
                }
                if(null==stateDto.getGivebackMarkedID()
                        ||"".equals(stateDto.getGivebackMarkedID())){
                    throw new ServiceException("赠送标记人ID不能为空", RestConst.ErrorCode.FORM_FAIL);
                }
                verifyMD5(stateDto.getId());  //验证MD5加密信息
                stateDto.setGivebackTime(CommonUtils.getCurTimestamp());
                stateDto.setState(8);
                break;
            case 9://销售
                OrderInfoBorrow order9 = orderInfoBorrowMapper.selectByPrimaryKey(stateDto.getId());
                if (order9.getState() != 6) {
                    throw new ServiceException("订单状态参数有误，不能赠送", RestConst.ErrorCode.FORM_FAIL);
                }
                if(null==stateDto.getGivebackMarkedID()
                        ||"".equals(stateDto.getGivebackMarkedID())){
                    throw new ServiceException("销售标记人ID不能为空", RestConst.ErrorCode.FORM_FAIL);
                }
                verifyMD5(stateDto.getId());  //验证MD5加密信息
                List<OrderBorrowItem> itemList3 = orderBorrowItemMapper.selectByOrderID(stateDto.getId());
                for (OrderBorrowItem item : itemList3) {//恢复库存
                    goodsService.changeInventory(3, item.getGoodsID(), item.getSkuID(), item.getQty());
                }
                stateDto.setGivebackTime(CommonUtils.getCurTimestamp());
                stateDto.setState(9);
                break;
            default:
                throw new ServiceException("状态参数传入有误", RestConst.ErrorCode.FORM_FAIL);
        }
        orderInfoBorrowMapper.updateStateByPrimaryKey(stateDto);
        return true;
    }

    /**
     * 验证订单加密信息
     *
     * @param orderID
     */
    private void verifyMD5(Long orderID) {
        OrderInfoBorrow orderInfo = orderInfoBorrowMapper.selectByPrimaryKey(orderID);
        String md5 = CommonUtils.MD5(getAmountForMD5(orderInfo.getAmount().toString()) + orderInfo.getQty() + ProConstants.salt);
        if (!orderInfo.getMd5().equals(md5)) {
            throw new ServiceException("借货订单价格或商品数量有误，请联系管理员", RestConst.ErrorCode.DATABASE_ERROR);
        }

        List<OrderBorrowItem> itemList = orderBorrowItemMapper.selectByOrderID(orderID);
        for (OrderBorrowItem item : itemList) {
            String md51 = CommonUtils.MD5(getAmountForMD5(item.getAmount().toString()) + item.getQty() + ProConstants.salt);
            if (!item.getMd5().equals(md51)) {
                throw new ServiceException("借货订单详情价格或商品数量有误，请联系管理员", RestConst.ErrorCode.DATABASE_ERROR);
            }
        }
    }

    /**
     * 查询用户借货列表
     * @param userID
     * @param state
     * @return
     */
    public List<OrderBorrowAndItem> selectOrderBorrowListByUser(Long userID,int state) {
        if(null==userID || userID<=0){
            throw new ServiceException("用户ID不能为空", RestConst.ErrorCode.FORM_FAIL);
        }
        OrderBorrowSelectDto selectDto = new OrderBorrowSelectDto();
        selectDto.setUserID(userID);
        selectDto.setState(state);
        selectDto.setCompanyID(SystemContext.getCompanyID());
        List<Long> ids=orderInfoBorrowMapper.selectUserOrderBorrowIDs(selectDto);
        if(ids.size()<1){
            List<OrderBorrowAndItem> nullList  = new ArrayList<>();
            return nullList;
        }
        return orderInfoBorrowMapper.selectOrderBorrowListByUser(ids);
    }

    /**
     * 未审核数量
     * @return
     */
    public Integer getNoAuditNum(Long userID,Long companyID,Integer organizationalLevel){
        //获取当前登录用户组织信息;过滤数据
        UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(userID);
        String orderBorrowAuditLevel=getBorrowSetting(companyID);
        if(!"2".equals(orderBorrowAuditLevel) && //未设置审核级别
                !"1".equals(orderBorrowAuditLevel)){
            return 0;
        }
        OrderBorrowSelectDto dto = new OrderBorrowSelectDto();
        dto.setOrganizationalLevel(Long.parseLong(organizationalLevel.toString()));
        if(organizationalLevel == 1
                &&"2".equals(orderBorrowAuditLevel)){//总行管理员&设置为二级审核
            dto.setBranchID(0l);
            dto.setTwoLevelBranchID(0l);
            dto.setSubbranchID(0l);
            dto.setStates("1,21");
//            dto.setCompanyID(companyID);
            dto.setCompanyID(SystemContext.getCompanyID());
            return orderInfoBorrowMapper.selectBorrowAuditCount(dto).intValue();
        }else if(organizationalLevel == 1
                &&"1".equals(orderBorrowAuditLevel)){//总行管理员&设置为一级审核
            dto.setStates("1,21");
//            dto.setCompanyID(companyID);
            dto.setCompanyID(SystemContext.getCompanyID());
            return orderInfoBorrowMapper.selectBorrowAuditCount(dto).intValue();
        }else if(organizationalLevel==2//分行管理员&设置为二级审核
                &&"2".equals(orderBorrowAuditLevel)){
            dto.setStates("1");
            //dto.setCompanyID(companyID);
            dto.setCompanyID(SystemContext.getCompanyID());
            dto.setBranchID(userInfoForOrderDto.getBranchID());
            dto.setTwoLevelBranchID(0l);
            dto.setSubbranchID(0l);
            return orderInfoBorrowMapper.selectBorrowAuditCount(dto).intValue();
        }else if(organizationalLevel==2//分行管理员&设置为一级审核
                &&"1".equals(orderBorrowAuditLevel)){
            return 0;
        }else if(organizationalLevel==3//二级分行管理员&设置为二级审核
                &&"2".equals(orderBorrowAuditLevel)){
            dto.setStates("1");
            //dto.setCompanyID(companyID);
            dto.setCompanyID(SystemContext.getCompanyID());
            dto.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
            dto.setSubbranchID(0l);
            return orderInfoBorrowMapper.selectBorrowAuditCount(dto).intValue();
        }else if(organizationalLevel==3//二级分行管理员&设置为一级审核
                &&"1".equals(orderBorrowAuditLevel)){
            return 0;
        }else if(organizationalLevel==4//支行管理员&设置为二级审核
                &&"2".equals(orderBorrowAuditLevel)){
            dto.setStates("1");
            //dto.setCompanyID(companyID);
            dto.setCompanyID(SystemContext.getCompanyID());
            dto.setSubbranchID(userInfoForOrderDto.getSubbranchID());
            return orderInfoBorrowMapper.selectBorrowAuditCount(dto).intValue();
        }else if(organizationalLevel==4//支行管理员&设置为一级审核
                &&"1".equals(orderBorrowAuditLevel)){
            return 0;
        }
        return 0;
    }

    /**
     * 借货审核列表
     * @param dto
     * @return
     */
    public Object selectOrderBorrowAuditList(
            OrderBorrowSelectDto dto, Integer pageNum, Integer pageSize){
        if("".equals(dto.getUserID()) || null==dto.getUserID()){
            throw new ServiceException("当前登录用户ID不能为空");
        }
        //审核级别
        String orderBorrowAuditLevel=getBorrowSetting(dto.getCompanyID());
        if(!"2".equals(orderBorrowAuditLevel) &&
                !"1".equals(orderBorrowAuditLevel)){
            throw CommonTools.createException(ErrorCodeEnum.noSettingOrderBorrowAuditLevel);
        }
        //角色组织级别
        Long organizationalLevel=dto.getOrganizationalLevel();

        //审核设置为1表示无需上级审核,则不对上级显示数据
        //organizationalLevel 1总行 2分行 3二级分行 4支行
        if("1".equals(orderBorrowAuditLevel)){
            if(2==organizationalLevel||3==organizationalLevel||4==organizationalLevel){
                return retNullPage();
            }
        }

        //获取当前登录用户组织信息;过滤数据
        UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(dto.getUserID());
        switch (organizationalLevel.intValue()){
            case 1://总部
                if("2".equals(orderBorrowAuditLevel)){//二级审核开启
                    dto.setBranchID(0l);
                    dto.setTwoLevelBranchID(0l);
                    dto.setSubbranchID(0l);
                }
                break;
            case 2://分行
                dto.setBranchID(userInfoForOrderDto.getBranchID());
                dto.setTwoLevelBranchID(0l);
                dto.setSubbranchID(0l);
                break;
            case 3://二级分行
                dto.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
                dto.setSubbranchID(0l);
                break;
            case 4://支行
                dto.setSubbranchID(userInfoForOrderDto.getSubbranchID());
                break;
        }

        PageHelper.startPage(pageNum, pageSize);//分页初始化

        dto.setCompanyID(SystemContext.getCompanyID());
        //查询审核列表id
        List<Long> ids=orderInfoBorrowMapper.selectBorrowAuditIDs(dto);

        if(ids.size()<1){
            return retNullPage();
        }

        Long total =orderInfoBorrowMapper.selectBorrowAuditCount(dto);

        //根据id查询审核列表
        List<OrderBorrowAndItem>InfoList =  orderInfoBorrowMapper.selectOrderBorrowAuditList(ids);
        PageInfo<OrderBorrowAndItem> page = new PageInfo(InfoList);
        page.setPages(calcPages(total,pageSize));
        page.setTotal(total);
        return page;
    }


    /**
     * 借货管理列表
     * @param dto
     * @return
     */
    public Object selectOrderBorrowList(
            OrderBorrowSelectDto dto,Integer pageNum, Integer pageSize){
        dto.setCompanyID(SystemContext.getCompanyID());
        PageHelper.startPage(pageNum, pageSize);//分页初始化
        List<Long> ids=orderInfoBorrowMapper.selectOrderBorrowIDs(dto);
        if(ids.size()<1){
            return retNullPage();
        }
        dto.setCompanyID(SystemContext.getCompanyID());
        Long total=orderInfoBorrowMapper.selectOrderBorrowCount(dto);
        List<OrderBorrowAndItem>InfoList = orderInfoBorrowMapper.selectOrderBorrowList(ids);
        PageInfo<OrderBorrowAndItem> page = new PageInfo(InfoList);
        page.setPages(calcPages(total,pageSize));
        page.setTotal(total);
        return page;
    }

    /**
     * 返回空pager对象
     * @return
     */
    private  PageInfo<OrderBorrowAndItem> retNullPage(){
        List<OrderBorrowAndItem> nullList  = new ArrayList<>();
        PageInfo<OrderBorrowAndItem> nullPage = new PageInfo(nullList);
        return nullPage;
    }

    private int calcPages(Long total,Integer pageSize){
        double a=total.doubleValue()/Double.parseDouble(pageSize.toString());
        if(total%pageSize==0){
            return (int)a;
        }else{
            return (int)a+1;
        }
    }

    /**
     * 新增订单-校验收货信息
     * @param addOrderBorrowDto
     */
    private String checkContactForAddOrder(AddOrderBorrowDto addOrderBorrowDto){
        if(null==addOrderBorrowDto.getShortAddress()
                || "".equals(addOrderBorrowDto.getShortAddress())){
            return "收货短地址不能为空";
        }
        if(null==addOrderBorrowDto.getProvince()
                || addOrderBorrowDto.getProvince()<0){
            return "省Code不能为空";
        }
        if(null==addOrderBorrowDto.getCity()
                || addOrderBorrowDto.getCity()<0){
            return "市Code不能为空";
        }
        if(null==addOrderBorrowDto.getDistrict()
                || addOrderBorrowDto.getDistrict()<0){
            return "区Code不能为空";
        }
        return "";
    }

    /**
     * 立即下单-校验收货信息
     * @param buyDto
     */
    private String checkContactForBuyNow(CopyOrDirectBorrowDto buyDto){
        if(null==buyDto.getDistrict()
                || buyDto.getDistrict()<0){
            return "区Code不能为空";
        }
        if(null==buyDto.getShortAddress()
                || "".equals(buyDto.getShortAddress())){
            return "收货短地址不能为空";
        }
        if(null==buyDto.getProvince()
                || buyDto.getProvince()<0){
            return "省Code不能为空";
        }
        if(null==buyDto.getCity()
                || buyDto.getCity()<0){
            return "市Code不能为空";
        }
        return "";
    }

    /**
     * erp查询借货
     * @param orderID
     * @return
     */
    public Object selectOrderBorrowErp(Long orderID){
        if(null==orderID || 1>orderID)
            throw new ServiceException("订单ID不能为空");
        List<BorrowInfoWithItems> list= orderInfoBorrowMapper.selectOrderBorrowErp(orderID);
        if (list.size()>0){
            for (BorrowInfoWithItems vo:list){//组装单位名称
                vo.setUnitName(getOrgName(Long.valueOf(vo.getUnit())));
                vo.setAccountCode(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));//固定自营
                for (BorrowItem bvo:vo.getItems()){//产品图片
                    if (null!=bvo.getPicture() && !"".equals(bvo.getPicture())){
                        //getImageService
                        bvo.setPicture(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.IMAGESERVICE.getCode())+bvo.getPicture());
                    }
                }
            }
        }
        return list.get(0);
    }

    /**
     * 获取借货设置
     * @param companyID
     * @return
     */
    private String getBorrowSetting(Long companyID){
        DataResult result = HttpUtil.httpGet(//获取借货订单审核级别
                ProConstants.getOrderBorrowAuditLevel + companyID, restTemplate);
        return result.getIsSuccess() == 1?result.getData().toString():"";
    }

    /**
     * 获取组织名称
     * @param oID
     * @return
     */
    private String getOrgName(Long oID){
        DataResult result = HttpUtil.httpGet(
                ProConstants.getOrganizational + oID, restTemplate);
        Map<String, Object> org = new HashMap<>();
        if (result.getIsSuccess() == 1) {
            org = (Map<String, Object>) result.getData();
        } else {
            throw new ServiceException("调用base服务查询用户组织信息失败", RestConst.ErrorCode.FORM_FAIL);
        }
        if(org==null){
            return "总部";
        }
        return org.get("organizationalName")==null ? "总部":org.get("organizationalName").toString();
    }

    /**
     * 直辖市特殊处理
     * @param province
     * @param city
     * @return
     */
    private Integer setCityCode(Integer province,Integer city){
        String ret="";
        if(province.toString().equals(city.toString())){
            ret=city.toString().substring(0,city.toString().length()-3);
            ret+="100";
            return Integer.parseInt(ret);
        }
        return city;
    }

    public Object selCompanyById(Long id){
        if(id == null || id == 0){
            throw new ServiceException("未获取到借货单号");
        }
        OrderInfoBorrow orderInfoBorrow = orderInfoBorrowMapper.selectByPrimaryKey(id);
        if(orderInfoBorrow == null){
            throw new ServiceException("未获取到借货单");
        }
        return  orderInfoBorrow.getCompanyID();

    }


}